from django.shortcuts import render
from django.views.decorators.http import require_GET, require_POST, require_http_methods
from utils.decorators import login_required
from df_cart.models import Cart
from django.http import JsonResponse
# Create your views here.


# /cart/add/                # 添加商品到购物车
@require_GET
@login_required
def cart_add(request):
    # 获取商品id和商品数
    goods_id = request.GET.get('goods_id')
    goods_count = request.GET.get('goods_count')
    # 获取用户id
    passport_id = request.session.get('passport_id')

    res = Cart.objects.add_one_cart_info(passport_id=passport_id, goods_id=goods_id,
                                         goods_count=int(goods_count))
    # 判断返回Json值
    if res:
        return JsonResponse({'res': 1})

    return JsonResponse({'res': 0})


@require_GET
@login_required
def cart_count(request):
    # 获取用户id
    passport_id = request.session.get('passport_id')
    # 获取购物车中商品数目
    res = Cart.objects.get_cart_count_by_passport(passport_id=passport_id)
    # 返回商品数目
    return JsonResponse({'res': res})


# /cart/
@login_required
def cart_show(request):
    # 获取用户id
    passport_id = request.session.get('passport_id')
    cart_list = Cart.objects.get_cart_list_by_passport(passport_id=passport_id)

    return render(request, 'df_cart/cart.html', {'cart_list': cart_list})


# /cart/update/?goods_id=商品id&goods_count=商品数目
@require_GET
@login_required
def cart_update(request):
    passport_id = request.session.get('passport_id')
    goods_id = request.GET.get('goods_id')
    goods_count = request.GET.get('goods_count')

    res = Cart.objects.update_one_cart_info(passport_id=passport_id, goods_id=goods_id, goods_count=goods_count)

    # 成功返回1， 失败返回0
    if res:
        return JsonResponse({'res': 1})
    else:
        return JsonResponse({'res': 0})


# /cart/del/?goods_id=商品id
@require_GET
@login_required
def cart_delete(request):
    passport_id = request.session.get('passport_id')
    goods_id = request.GET.get('goods_id')

    # 删除商品
    res = Cart.objects.delete_one_cart_info(passport_id=passport_id, goods_id=goods_id)
    if res:
        return JsonResponse({'res': 1})
    else:
        return JsonResponse({'res': 0})
